package com.apps.FileUpload.Local.service.Impl;

import cn.hutool.core.util.RandomUtil;
import com.apps.FileUpload.Local.config.FileUploadConfig;
import com.apps.FileUpload.Local.service.IFileUploadService;
import com.apps.FileUpload.Local.utils.FileUtils;
import com.apps.sexctption.NullException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class FileUploadServiceImpl implements IFileUploadService {

    @Autowired
    private FileUploadConfig uploadConfig;

    @Override
    public String save(MultipartFile file,String flod) {
        // 获得原始文件名+格式
        String fileName = file.getOriginalFilename();
        //截取文件名
        String fname = fileName.substring(0, fileName.lastIndexOf("."));
        //截取文件格式
        String format = fileName.substring(fileName.lastIndexOf(".") + 1);
        //获取当前时间(精确到毫秒)
        long MS = System.currentTimeMillis();
        String timeMS = String.valueOf(MS);
        //原文件名+当前时间戳作为新文件名
        String videoName = RandomUtil.randomNumbers(10)+timeMS + "." + format;
        String flodName = FileUtils.getFlodNameTodays();  //文件夹名称
        String filelocalPath = uploadConfig.getRootpath()+"\\"+flod+"\\"+ flodName +"\\";
        File f = new File(filelocalPath);
        if (!f.exists())
            f.mkdirs();
        if (!file.isEmpty()) {
            try {
                FileOutputStream fos = new FileOutputStream(filelocalPath + videoName);
                InputStream in = file.getInputStream();
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = in.read(bytes)) != -1) {
                    fos.write(bytes, 0, len);
                }
                fos.close();
                in.close();
            } catch (Exception e) {
                throw new NullException(e.getMessage());
            }
        }else
            throw new NullException("文件上传失败,传输的数据为空");

        return uploadConfig.getPrefix()+"\\"+flod+"\\"+flodName+"\\"+videoName;
    }

    public static void main(String... args)
    {
        Date date = new Date();
        String dateOne = new SimpleDateFormat("yyyyMMdd").format(date);
        System.out.println(dateOne);
    }
}
